package bio.server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class BIOServer implements Runnable {

    private boolean stop = false;
    private final ServerSocket serverSocket;

    public BIOServer(ServerSocket socket) {
        this.serverSocket = socket;
    }

    @Override
    public void run() {

        if (!serverSocket.isClosed()) {
            System.out.println("server start succeeded");
            System.out.println("address: " + serverSocket.getInetAddress().getHostAddress() + ":" + serverSocket.getLocalPort());
        }

        while (!stop) {
            try {
                // accept方法会一直阻塞，直到有socket成功建立连接
                Socket socket = serverSocket.accept();

                if (socket.isConnected()) {
                    // 从socket中获取输入流, 并处理
                    BufferedReader inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    String a;
                    while ((a = inputStream.readLine()) != null) {
                        System.out.println(a);
                    }
                    // 完成读取
                    socket.shutdownInput();

                    // 获取输出流, 响应客户端
                    OutputStream outputStream = socket.getOutputStream();
                    outputStream.write("server accept".getBytes());
                    outputStream.flush();
                    // 完成写入
                    socket.shutdownOutput();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("server stop succeeded");
    }
}
